package com.petshop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.petshop.mapper.VoucherMapper;
import com.petshop.pojo.SeckillVoucher;
import com.petshop.pojo.Voucher;
import com.petshop.service.SeckillVoucherService;
import com.petshop.service.VoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.petshop.utils.RedisConstant.SECKILL_STOCK_KEY;

/**
 * @author 20289
 * @description 针对表【tb_voucher】的数据库操作Service实现
 * @createDate 2025-03-30 21:33:13
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher>
        implements VoucherService {

    private final SeckillVoucherService seckillVoucherService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public VoucherServiceImpl(SeckillVoucherService seckillVoucherService) {
        this.seckillVoucherService = seckillVoucherService;
    }

    /**
     * 新增秒杀优惠券
     *
     * @param voucher
     * @return
     */
    @Override
    public void addSeckillVoucher(Voucher voucher) {
        //因为秒杀券属于优惠券，所有要新增一张优惠券voucher
        save(voucher);
        //接着保存秒杀券的信息到秒杀券信息表里
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        //改进秒杀业务，写入优惠券库存信息到redis里
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), String.valueOf(String.valueOf(voucher.getStock())));
    }
}




